package com.example.service.impl;

import com.example.mapper.EmpMapper;
import com.example.pojo.Emp;
import com.example.service.LoginService;
import com.example.util.Constant;
import com.example.util.JwtTokenUtil;
import com.example.vo.ResultVo;
import com.example.vo.reqvo.UserLoginParams;
import com.example.vo.respvo.EmpBasicInfoVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录实现类
 *
 * @author wsl
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource(name = "userDetailsService")
    private UserDetailsService userDetailsService;

    @Resource(name = "passwordEncoder")
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private EmpMapper empMapper;

    @Override
    public ResultVo login(UserLoginParams userLoginParams, HttpServletRequest request) {
        //1.验证码校验
        if(!checkCaptcha(userLoginParams.getCode(),request)){
            return ResultVo.error("验证码错误");
        }
        //2.查询用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(userLoginParams.getUsername());
        if(userDetails==null || !passwordEncoder.matches(userLoginParams.getPassword(),userDetails.getPassword())){
            return ResultVo.error("用户名或密码错误");
        }
        if(!userDetails.isEnabled()){
            return ResultVo.error("账号被禁用，请联系管理员！");
        }

        //3.更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        //返回登录员工的信息
        Emp emp = new Emp();
        BeanUtils.copyProperties(userDetails,emp);
        HttpSession session = request.getSession();
        session.setAttribute(Constant.CURRENT_USER,userLoginParams.getUsername());
        session.setAttribute(Constant.CURRENT_USER_ID,emp.getId());
        emp.setPassword(null);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token",token);
        tokenMap.put("tokenHead",tokenHead);
        tokenMap.put("empInfo",emp);
        return ResultVo.success("登录成功",tokenMap);
    }

    @Override
    public EmpBasicInfoVo getLoginUserInfo(HttpServletRequest request) {
        String userId = jwtTokenUtil.getUserIdFormToken(request);
        return empMapper.selectLoginUserInfo(userId, "emp_status");
    }

    /**
     * 验证码校验
     * @param code
     * @param request
     * @return
     */
    public boolean checkCaptcha(String code,HttpServletRequest request){
        String captcha = (String) request.getSession().getAttribute("captcha");
        return StringUtils.isNotEmpty(code) && code.equalsIgnoreCase(captcha);
    }
}
